<template>
  <div class="system-client-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
      <el-form ref="clientDialogFormRef" :model="state.ruleForm" size="default" label-width="90px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="客户端ID" prop="clientId" :rules="[{ required: true, message: '请输入客户端ID', trigger: 'blur' }]">
              <el-input v-model="state.ruleForm.clientId" placeholder="请输入客户端ID" clearable :disabled="state.dialog.type === 'edit'"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="客户端名称" prop="clientName" :rules="[{ required: true, message: '请输入客户端名称', trigger: 'blur' }]">
              <el-input v-model="state.ruleForm.clientName" placeholder="请输入客户端名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="客户端类型" prop="clientType" :rules="[{ required: true, message: '请选择客户端类型', trigger: 'change' }]">
              <el-select v-model="state.ruleForm.clientType" placeholder="请选择客户端类型" style="width: 100%" :disabled="state.dialog.type === 'edit'">
                <el-option label="机密客户端" value="confidential"></el-option>
                <el-option label="公开客户端" value="public"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="认证方法" prop="tokenEndpointAuthMethod">
              <el-select v-model="state.ruleForm.tokenEndpointAuthMethod" placeholder="请选择认证方法" style="width: 100%">
                <el-option label="客户端密钥基础认证" value="client_secret_basic"></el-option>
                <el-option label="客户端密钥POST认证" value="client_secret_post"></el-option>
                <el-option label="无认证" value="none"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="重定向URI" prop="redirectUris" :rules="[{ required: true, message: '请输入重定向URI', trigger: 'blur' }]">
              <el-input
                v-model="state.redirectUrisText"
                type="textarea"
                placeholder="请输入重定向URI，多个URI用换行分隔"
                :rows="3"
                @blur="handleRedirectUrisChange"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="授权类型" prop="grantTypes">
              <el-checkbox-group v-model="state.ruleForm.grantTypes">
                <el-checkbox label="authorization_code">授权码模式</el-checkbox>
                <el-checkbox label="refresh_token">刷新令牌</el-checkbox>
                <el-checkbox label="client_credentials">客户端凭证</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="响应类型" prop="responseTypes">
              <el-checkbox-group v-model="state.ruleForm.responseTypes">
                <el-checkbox label="code">授权码</el-checkbox>
                <el-checkbox label="id_token">ID令牌</el-checkbox>
                <el-checkbox label="token">访问令牌</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="作用域" prop="scopes">
              <el-checkbox-group v-model="state.ruleForm.scopes">
                <el-checkbox 
                  v-for="scope in scopeOptions" 
                  :key="scope.value" 
                  :label="scope.value"
                >
                  {{ scope.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
            <el-form-item label="访问令牌TTL" prop="accessTokenTtl">
              <el-input-number v-model="state.ruleForm.accessTokenTtl" :min="60" :max="86400" placeholder="秒" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
            <el-form-item label="刷新令牌TTL" prop="refreshTokenTtl">
              <el-input-number v-model="state.ruleForm.refreshTokenTtl" :min="3600" :max="2592000" placeholder="秒" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
            <el-form-item label="ID令牌TTL" prop="idTokenTtl">
              <el-input-number v-model="state.ruleForm.idTokenTtl" :min="60" :max="86400" placeholder="秒" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="状态" prop="status">
              <el-switch v-model="state.ruleForm.status" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="描述" prop="description">
              <el-input v-model="state.ruleForm.description" type="textarea" placeholder="请输入客户端描述" :rows="3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemClientDialog">
import { reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { createClient, updateClient } from '/@/api/oidc/clients';
import { getScopeOptions } from '/@/api/oidc/scopes';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const clientDialogFormRef = ref();
const scopeOptions = ref([]);
const state = reactive({
  ruleForm: {
    clientId: '',
    clientName: '',
    clientType: 'confidential',
    redirectUris: [],
    grantTypes: ['authorization_code', 'refresh_token'],
    responseTypes: ['code'],
    scopes: ['openid', 'profile'],
    tokenEndpointAuthMethod: 'client_secret_basic',
    accessTokenTtl: 3600,
    refreshTokenTtl: 86400,
    idTokenTtl: 3600,
    status: 1,
    description: '',
  },
  redirectUrisText: '',
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
});

// 处理重定向URI文本变化
const handleRedirectUrisChange = () => {
  state.ruleForm.redirectUris = state.redirectUrisText
    .split('\n')
    .map(uri => uri.trim())
    .filter(uri => uri.length > 0);
};

// 打开弹窗
const openDialog = (row?: any) => {
  if (row) {
    state.ruleForm = { ...row };
    state.redirectUrisText = row.redirectUris ? row.redirectUris.join('\n') : '';
    state.dialog.type = 'edit';
    state.dialog.title = '修改客户端';
    state.dialog.submitTxt = '修 改';
  } else {
    state.ruleForm = {
      clientId: '',
      clientName: '',
      clientType: 'confidential',
      redirectUris: [],
      grantTypes: ['authorization_code', 'refresh_token'],
      responseTypes: ['code'],
      scopes: ['openid', 'profile'],
      tokenEndpointAuthMethod: 'client_secret_basic',
      accessTokenTtl: 3600,
      refreshTokenTtl: 86400,
      idTokenTtl: 3600,
      status: 1,
      description: '',
    };
    state.redirectUrisText = '';
    state.dialog.type = 'add';
    state.dialog.title = '新增客户端';
    state.dialog.submitTxt = '新 增';
  }
  state.dialog.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 提交
const onSubmit = () => {
  clientDialogFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    
    handleRedirectUrisChange();
    
    try {
      if (state.dialog.type === 'add') {
        await createClient(state.ruleForm);
        ElMessage.success('新增成功');
      } else {
        await updateClient(state.ruleForm.id, state.ruleForm);
        ElMessage.success('修改成功');
      }
      closeDialog();
      emit('refresh');
    } catch (error) {
      console.error('操作失败:', error);
    }
  });
};

// 获取作用域选项
const loadScopeOptions = async () => {
  try {
    const response = await getScopeOptions();
    scopeOptions.value = response.data || [];
  } catch (error) {
    console.error('获取作用域选项失败:', error);
    // 如果获取失败，使用默认选项
    scopeOptions.value = [
      { value: 'openid', label: 'OpenID' },
      { value: 'profile', label: '用户信息' },
      { value: 'roles', label: '角色' },
      { value: 'permissions', label: '权限' }
    ];
  }
};

// 组件挂载时获取作用域选项
onMounted(() => {
  loadScopeOptions();
});

// 暴露变量
defineExpose({
  openDialog,
});
</script>